package client

import (
	"60321/pkg/models"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"time"
)

func InitDB(appConfig *Config) *gorm.DB {
	dsn := appConfig.Database.Dsn
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("database connection error: %v", err)
	}
	sqlDB, err := db.DB()
	if err != nil {
		log.Fatalf("database error: %v", err)
	}
	sqlDB.SetMaxIdleConns(appConfig.Database.MaxIdleConnes)
	sqlDB.SetMaxOpenConns(appConfig.Database.MaxOpenConnes)
	sqlDB.SetConnMaxLifetime(time.Hour)
	err = db.AutoMigrate(&models.CityModel{},
		&models.UserModel{},
		&models.TicketModel{},
		&models.TaxiModel{},
		&models.UserTicketModel{},
		&models.AdjacentCityModel{},
		&models.TicketCityModel{},
		&models.CityTaxiModel{})
	if err != nil {
		log.Fatalf("database error: %v", err)
	}
	fmt.Println("表结构建立成功！")
	return db
}
